﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;

namespace DNA.Mvc.Data.Entity
{
    public class WebRepository : EntityRepository<Web>, IWebRepository
    {
        public WebRepository() : base() { }

        public WebRepository(DB dbContext) : base(dbContext) { }

        /// <summary>
        /// Get Web by specified the web name.
        /// </summary>
        /// <param name="name">The specified web site name.</param>
        /// <returns></returns>
        public virtual Web GetByName(string name)
        {
            return Find(w => w.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// Create a new web object and save to database.
        /// </summary>
        /// <param name="t">Specified the web object to save.</param>
        /// <returns>Return a saved new web object.</returns>
        public override Web Create(Web t)
        {
            if (string.IsNullOrEmpty(t.Owner))
                throw new ArgumentNullException("Web.Owner");

            if (string.IsNullOrEmpty(t.Name))
                throw new ArgumentNullException("Web.Name");

            if (this.Contains(w => w.Name.Equals(t.Name)))
                throw new WebSiteIsExistsException(t.Name);

            if ((t.Created == null) || t.Created.Equals(DateTime.MinValue))
                t.Created = DateTime.UtcNow;

            if ((t.MostOnlined == null) || t.MostOnlined.Equals(DateTime.MinValue))
                t.MostOnlined = DateTime.UtcNow;

            if (string.IsNullOrEmpty(t.Theme))
                t.Theme = "default";

            if (string.IsNullOrEmpty(t.AllowExtensions))
                t.AllowExtensions = ".txt|.jpg|.gif|.png|.zip|.rar";

            return base.Create(t);
        }

        public override Web Update(Web web)
        {
            if (web.Properties.Count == 0)
                web.Data = "";
            else
                web.Data = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(web.Properties);

            return base.Update(web);
        }
    }
}
